package com.magima.utils.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Vector;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

import android.widget.ImageView;

import com.magima.utils.image.GifHelper.GifFrame;

public class GifUtil {
	private static PlayGifTask mGifTask;
	private static Vector<GifFrame> frames = null;
	private static boolean read_gif_done = false;
	
	/**
	 * 解码GIF图片
	 * 
	 * @param is
	 * @return
	 */
	public static GifFrame[] getGif(InputStream is, Handler handler) {
		GifHelper gifHelper = new GifHelper(handler);
		if (GifHelper.STATUS_OK == gifHelper.read(is)) {
			return gifHelper.getFrames();
		}
		return null;
	}

	/**
	 * 判断图片是否为GIF格式
	 * 
	 * @param is
	 * @return
	 */
	public static boolean isGif(InputStream is) {
		GifHelper gifHelper = new GifHelper();
		return gifHelper.isGif(is);
	}
	
	@SuppressLint("HandlerLeak")
	private static Handler mGifHandler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case GifHelper.ADD_ONE_FRAME : 
				GifFrame f = (GifFrame)msg.obj;
                if(frames != null) {
                    frames.addElement(f);
                }
				break;
			case GifHelper.ADD_FRAME_DONE : 
				read_gif_done = true;
				break;
			}
		}
	};
	
	public static void setGif(ImageView img, final File file){
		read_gif_done = false;
		frames = new Vector<GifFrame>();
		
		mGifTask = new PlayGifTask(img);
		mGifTask.start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					InputStream is = new FileInputStream(file);
					getGif(is, mGifHandler);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	

	public static void setGif(ImageView img, final Context context, final int rId){
		read_gif_done = false;
		frames = new Vector<GifFrame>();

		mGifTask = new PlayGifTask(img);
		mGifTask.start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					InputStream is = context.getResources().openRawResource(rId);
					getGif(is, mGifHandler);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	public static void stopGif(){
		if(mGifTask != null)
			mGifTask.stop();
	}
	
	private static class PlayGifTask implements Runnable {
        private int i = 0;
        private ImageView iv;
        private Vector<GifFrame> mFrames;

        public PlayGifTask(ImageView iv) {
            this.iv = iv;
        }

        @Override
        public void run() {
            if(frames == null || frames.size() == 0){
        		if(iv != null)
        			iv.postDelayed(this, 30);
        		return;
        	}
        	
        	Bitmap bm = frames.get(i).image;
        	if(bm != null && !bm.isRecycled()){
        		iv.setImageBitmap(bm);
        	}
            
            iv.postDelayed(this, frames.get(i++).delay);
            if ( i >= frames.size() && !read_gif_done)
            	i = frames.size()-1;
            else
            	i %= frames.size();
        }
        
        public void start() {
            iv.post(this);
        }
        
        public void stop() {
            if(null != iv){
            	iv.removeCallbacks(this);
                iv = null;
            }

            if(null != frames) {
                for(GifFrame frame : frames) {
                    if(frame.image != null && !frame.image.isRecycled()) {
                        frame.image.recycle();
                        frame.image = null;
                    }
                }
                frames = null;
            }
        }
    }
}
